<?php
function lilina_userapi_favicon($args)
{
    extract($args);
    if (!isset($location)) {
        $msg = xarML('Invalid Parameter Count');
        xarErrorSet(XAR_SYSTEM_EXCEPTION, 'BAD_PARAM', new SystemException($msg));
        return;
    }
    $empty_ico_data = base64_decode(
    'AAABAAEAEBAAAAEACABoBQAAFgAAACgAAAAQAAAAIAAAAAEACAAAAAAAQAEAAAAAAAAAAAAAAAAA' .
    'AAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' .
    'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' .
    'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' .
    'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' .
    'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' .
    'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' .
    'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' .
    'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' .
    'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' .
    'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' .
    'AAAA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AAD//wAA//8AAP//' .
    'AAD//wAA//8AAP//AAD//wAA//8AAP//AAD//wAA//8AAP//AAA=');
    
	$ico_url = getFaviconURL($location) ;
	if(!$ico_url) {
		return false ;
	}
	
    $cached_ico = 'modules/lilina/xarimages/' . md5($ico_url) . ".ico" ;
	
    $cachetime = 7 * 24 * 60 * 60; // 7 days
    	// echo "<br> $ico_url , $cached_ico " ;
	// Serve from the cache if it is younger than $cachetime
	if (file_exists($cached_ico) && (time() - $cachetime < filemtime($cached_ico))) return $cached_ico ;
	if (!$data = @file_get_contents($ico_url)) $data=$empty_ico_data ;
	if (stristr($data,'html')) $data=$empty_ico_data ;
	$fp = fopen($cached_ico,'w') ;
	fputs($fp,$data) ;
	fclose($fp) ;
	return $cached_ico ;
}

function getFaviconURL($location){
    if(!$location){
        return false;
    }else{
	$url_parts = parse_url($location);
	$full_url = "http://$url_parts[host]";
	if(isset($url_parts['port'])){
		$full_url .= ":$url_parts[port]";
	}
	$favicon_url = $full_url . "/favicon.ico" ;
    }
    return $favicon_url;
}
?>